define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var tip    = require('@base/tip');
	var common = require('modules/common');
	var popwin	= require('@base/dialog');

	// 条件组
	var CONDITION = [
		{
			'title': LANG('操作相关：'),
			'items': [
				{'name': LANG('添加层级'), 'id':'', 'op': 'addLevel'},
				{'name': LANG('删除层级'), 'id':'', 'op': 'removeLevel', 'class': 'link'},
				{'name': LANG('引用条件'), 'id':'', 'op': 'refLevel'},
			]
		},
		{
			'title': LANG('通用条件：'),
			'items': [
				{'name': LANG('交易类型'), 'id':'BidType', 'op': ''},
				{'name': LANG('交易订单'), 'id':'Deals', 'op': ''},
				// {'name': LANG('渠道'), 'id':'Adx', 'op': ''},
				{'name': LANG('RTB 广告位'), 'id':'RTBSpot', 'op': ''},
				{'name': LANG('订单广告位'), 'id':'DealSpot', 'op': ''},
				{'name': LANG('媒体广告位'), 'id':'MediaSpot', 'op': ''},
				{'name': LANG('地区'), 'id':'Zone', 'op': ''},
				{'name': LANG('投放日期'), 'id':'Time', 'op': ''},
				{'name': LANG('投放日程'), 'id':'TimeSet', 'op': ''},
				{'name': LANG('自有人群'), 'id':'NPeople', 'op': ''},
				{'name': LANG('IP地址段'), 'id':'IpSections', 'op': ''},
				{'name': LANG('上网场景'), 'id':'Scene', 'op': ''},
				// {'name': LANG('媒体分类'), 'id':'', 'op': ''},
				{'name': LANG('视频定向'), 'id':'VideoDirect', 'op': ''},
				// {'name': LANG('展示形式'), 'id':'ViewType', 'op': ''},
				// {'name': LANG('屏次'), 'id':'Screen', 'op': ''},
				{'name': LANG('百度指数'), 'id':'HotWord', 'op': ''},
				{'name': LANG('百度tag_id'), 'id':'CustomizedUserTag', 'op': ''}
			]
		},
		{
			'title': LANG('WEB 条件：'),
			'items': [
				{'name': LANG('WEB 三方人群'), 'id':'TBPeople', 'op': ''},
				// {'name': LANG('WEB 秒针人群'), 'id':'MZPeople', 'op': ''},
				{'name': LANG('WEB 其他人群'), 'id':'BdxPeople', 'op': ''},
				{'name': LANG('WEB 重定向'), 'id':'Character', 'op': ''},
				{'name': LANG('WEB 客户端'), 'id':'Client', 'op': ''},
				// {'name': LANG('WEB 温度'), 'id':'Temperature', 'op': ''},
				// {'name': LANG('WEB 湿度'), 'id':'HumidityLevels', 'op': ''},
				// {'name': LANG('WEB 空气指数'), 'id':'ApiLevels', 'op': ''},
				// {'name': LANG('WEB 温差'), 'id':'TemperatureDiff', 'op': ''},
				{'name': LANG('WEB 页面关键词'), 'id':'PageKeyword', 'op': ''},
				// {'name': LANG('WEB 用户关键词'), 'id':'UserKeyword', 'op': ''}
			]
		},
		{
			'title': LANG('APP 条件：'),
			'items': [
				{'name': LANG('APP 其他人群'), 'id':'APP_BdxPeople', 'op': ''},
				{'name': LANG('APP 重定向'), 'id':'APP_Character', 'op': ''},
				{'name': LANG('APP 网络类型'), 'id':'APP_Network', 'op': ''},
				{'name': LANG('APP 设备'), 'id':'APP_DeviceType', 'op': ''},
				{'name': LANG('APP 操作系统'), 'id':'APP_OSType', 'op': ''},
				{'name': LANG('APP LBS 定向'), 'id':'APP_LBS', 'op': ''},
				{'name': LANG('APP 网络运营商'), 'id':'APP_Carriers', 'op': ''},
			]
		}
	]


	// 条件层级组件
	var ConditionLevel = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'M-promotionConditionLevel',
				'max': 5,
				'bracketL': '( ',
				'bracketR': ' )'

			});

			// this.$currentTitle = '';	// 当前子条件title
			this.$currentAnchor = null; // 当前锚点
			this.$levelData = {};	// 平铺所有条件数据记录
			this.$levelLogic = {};	// 平铺所有逻辑元素记录
			this.$hasRef = [];	// 是否引用了条件数组
			this.$timeFn = null; // 缓存单击事件里的计时事件返回的id

			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var el = self.getDOM();
			var c = self.getConfig();

			// 顶层
			var level = $([
				'<div class="level">',
					'<a data-level="0" data-uid="L0"><i class="uk-icon-plus-square"/></a>',
				'</div>'
			].join('')).appendTo(el);

			var doms = self.$doms = {
				'level': level,	// 最顶层
				'anchor': level.find('>a')	// 最顶层+号
			};
			self.$currentAnchor = doms.anchor; // 设置最顶层+号为当前锚点

			self.uiProxy(el, '.level a', 'click', 'eventAddItem');
			self.uiProxy(el, '.logic', 'click', 'eventChangeLogic');
			self.uiProxy(el, '.desc', 'click', 'eventShowDetail');
			// 双击条件，进入编辑页面
			self.uiProxy(el, '.desc', 'dblclick', 'eventShowEdit');

			self.buildPanel();
			self.buildDetailPanel();
		},
		// 构建公用子条件选择面板
		buildPanel: function(){
			var self = this;
			var doms = self.$doms;
			// 构建弹层
			if (!self.get('tooltip')){
				doms.tooltipCon = self.create('tooltip', ConditionTip, {
					'anchor': doms.anchor,
					'autoShow': false,
					'pos': 'bL', // 定位模式
					// 'width': 820,
					// 'height': 380,
					'width': 750,
					'height': 450,
					'offsetY': 5,
					'offsetX': 1,
					'hideDuration': 0,
					'arrowAlign': 'left',
					'arrowAlignPixel': 20,
					'autoHide': 'click_body click_anchor'
				}).getContainer();
			}

			// 构建弹层内容
			util.each(CONDITION, function(group){
				if(group){
					var html = $([
						'<div class="M-formConGroup M-promotionConditionLevelPanel">',
							'<div class="group-label title">',
								'<label>' +group.title+ '</label>',
							'</div>',
							'<div class="group-content">',
								'<ul class="content"/>',
							'</div>',
						'</div>',
					].join('')).appendTo(doms.tooltipCon);

					var con = html.find('.group-content > ul');

					util.each(group.items, function(item){
						var elem = $([
							'<li data-id="'+item.id+'">',
								'<a title="'+item.name+'" >' + item.name + '</a>',
							'</li>'
						].join('')).appendTo(con).find('a').attr({
							'data-op': item.op,
							'data-id': item.id
						}).addClass(item.class);
					});
				}
			});

			self.uiProxy(doms.tooltipCon, 'a[data-op]', 'click', 'eventOperateLevel');

			// 子条件选项设置弹窗
			self.createAsync('settingsPop', 'promotion/popwin/settings.main');
		},
		// 条件详情面板
		buildDetailPanel: function(){
			var self = this;
			var doms = self.$doms;
			// 构建弹层
			if (!self.get('detailTip')){
				doms.detailTipCon = self.create('detailTip', tip.tooltip, {
					'anchor': doms.anchor,
					'autoShow': false,
					'pos': 'bL', // 定位模式
					'width': 400,
					'height': 200,
					'offsetY': 5,
					'offsetX': 1,
					'hideDuration': 0,
					'arrowAlign': 'left',
					'arrowAlignPixel': 20,
					'autoHide': 'click_body click_anchor'
				}).getContainer();
			}

			var con = $([
				'<div class="M-promotionConditionDetailPanel">',
					'<div class="detailCon">',

					'</div>',
					'<div class="buttonCon">',
						'<button class="btn btn-default edit">'+LANG('修改')+'</button>',
						'<button class="btn btn-default remove">'+LANG('删除')+'</button>',
					'</div>',
				'</div>'
			].join('')).appendTo(doms.detailTipCon);


			self.uiBind(con.find('.edit'), 'click', 'eventEditConditon');
			self.uiBind(con.find('.remove'), 'click', 'eventRemoveConditon');
		},
		// 增加层
		addLevel: function(anchor){
			var self = this;
			var c = self.getConfig();
			var lv = $([
				'<div class="lv">',
					c['bracketL'],
					'<a><i class="uk-icon-plus-square"/></a>',
					c['bracketR'],
				'</div>'
			].join(''));

			if(anchor){
				var level = +anchor.attr('data-level')+1;
				if(level > 3){
					pubjs.alert('不能超过三层');
					return self;
				}
				lv.addClass('level'+level);
				lv.insertBefore(anchor);
				var logic = self.buildLogic(lv);
				self.updateLogic(lv.prev('.logic'));

				lv.find('a').attr({
					'data-level': level,
					'data-uid': self.getUid(anchor)
				});
			}
			return lv.find('a');
		},
		// 删除层
		removeLevel: function(anchor){
			if(anchor){
				var level = +anchor.attr('data-level');
				if(!level){
					pubjs.alert(LANG('不能删除顶层'));
				}else{
					var self = this;
					var parent = anchor.parent();
					var prev_logic = parent.prev('.logic');
					var subs = parent.find('[data-uid]');
					$.each(subs, function(idx, item){
						var uid = $(item).attr('data-uid');
						delete self.$levelData[uid];
						delete self.$levelLogic[uid];
					});

					parent.next('.logic').remove();
					parent.remove();
					this.updateLogic(prev_logic);

					// 删除同层的条件

				}
			}
			return this;
		},
		// 引用层
		refLevel: function(anchor){
			// 子条件选项设置弹窗
			var self = this;
			if(!self.get('refCondition')){
				self.create('refCondition', RefCondition, {
					'selectEvent': 'refCondition'
				});
			}
			self.get('refCondition').show();
			self.$.tooltip.hide();
			return self;
		},
		// 打开+号操作层
		eventAddItem: function(evt, elm){
			this.$currentAnchor = $(elm);
			this.$.tooltip.update({'anchor': $(elm)}).show();
			return false;
		},
		// +号操作层选项点击事件
		eventOperateLevel: function(evt, elm){
			var currentAnchor = this.$.tooltip.getConfig('anchor');
			var op = $(elm).attr('data-op');
			var id = $(elm).attr('data-id');
			switch (op){
				case 'addLevel':
					this.addLevel(currentAnchor);
					break;
				case 'removeLevel':
					this.removeLevel(currentAnchor);
					break;
				case 'refLevel':
					this.refLevel(currentAnchor);
					break;
			}

			if(id){
				// this.$currentTitle = $(elm).text();
				this.$.settingsPop.reset().show().setTitle($(elm).text()).setType(id).setAnchor($(elm)).setEdit(false);
			}
			this.$.tooltip.hide();
			return false;
		},
		// 改变且或
		eventChangeLogic: function(evt, elm){
			// 同级且或一齐改变
			var logics = $(elm).parent().find('>.logic');
			$.each(logics, function(i, l){
				$(l).find('span:last').prependTo($(l)).show().next();
			});
			return false;
		},
		// 单击显示详细
		eventShowDetail: function(evt, elm){
			var self = this;
			var doms = self.$doms;
			var uid = $(elm).attr('data-uid');
			// 取消上次延时未执行的方法
			clearTimeout(self.$timeFn);
			// 执行延时,防止双击时触发单击事件
			self.$timeFn = setTimeout(function(){
				// 判断是否是引用的条件，引用的条件不能编辑，只能删除
				var isRef = $(elm).find('[data-ref="true"]').length > 0;
				doms.detailTipCon.find('.detailCon').html($(elm).attr('title'));
				doms.detailTipCon.find('.buttonCon button').attr('data-uid', uid)
					.filter('.edit')
					.toggle(!isRef).next()
					.toggleClass('ref', isRef);

				self.$.detailTip.update({'anchor': $(elm)}).show();
				return false;
			}, 300);
		},
		// 双击显示编辑条件页面
		eventShowEdit: function(evt, elm){
			// 判断是否是引用的条件，引用的条件不能编辑，只能删除
			var isRef = $(elm).find('[data-ref="true"]').length > 0;
			// 取消上次延时未执行的方法
			clearTimeout(this.$timeFn);
			if (isRef) {
				pubjs.alert(LANG('该条件不可编辑'));
			}
			else {
				this.eventEditConditon(evt, elm);
			}

			return false;
		},
		// 编辑条件事件
		eventEditConditon: function(evt, elm){
			var self = this;
			var uid = $(elm).attr('data-uid');
			var data = self.$levelData[uid];
			if(data){
				self.$.detailTip.hide();
				self.$.settingsPop.reset().show()
					.setTitle(data.Title)
					.setType(data.Type)
					.setAnchor($(elm))
					.setEdit(true)
					.setData(data);
			}
			return false;
		},
		// 删除条件事件
		eventRemoveConditon: function(evt, elm){
			var self = this;
			var uid = $(elm).attr('data-uid');
			var isRef = $(elm).hasClass('ref');
			delete self.$levelLogic[uid];
			delete self.$levelData[uid];

			// 删除引用
			if(isRef){
				self.$hasRef.pop();
			}

			var remove_elms = self.$doms.level.find('[data-uid="'+uid+'"]');
			var prev_logic = remove_elms.prev('.logic');
			remove_elms.remove();
			self.updateLogic(prev_logic);
			self.$.detailTip.hide();
			return false;
		},
		// 新增和编辑回调广播
		onSettingsSuccess: function(ev){
			var param = ev.param;
			if(param){
				if(param.IsEdit){
					this.updateLevelData(param);
				}else{
					this.setLevelData(param);
				}
			}
		},
		// 引用回调广播
		onRefCondition: function(ev){
			if(ev.param && ev.param.Data){
				var param = ev.param;
				var string = '[' + (param.Desc ? param.Desc : '') + ']';
				var data = {
					'Title': param.Name,
					'Desc': string,
					'Type': 'ConditionRef',
					'Relation': 1,
					'Data': param._id
				}
				this.$hasRef.push(true);
				this.setLevelData(data);
			}
		},
		// 获取标识
		getUid: function(anchor){
			if(anchor){
				var uid = anchor.attr('data-uid');
				var length = anchor.prevAll().not('.logic').length;
				var index = length ? length - 1 : 0;
			}
			return uid + '-' + index;
		},
		// 设置单条件数据
		setLevelData: function(data, anchor){
			var self = this;

			if(data){
				var anchor = anchor || self.$currentAnchor;
				// 描述文本
				// var desc = (data.Title || self.$currentTitle) + '：' + data.Desc;
				var desc = (data.Title || '') + '：' + data.Desc;
				var title = desc;

				if(data.Relation == 2){
					title = LANG('排除') + desc;
					desc = '<span class="font-danger">'+LANG('排除')+'</span>' + desc;
				}

				if(data.Type == 'ConditionRef'){
					title = LANG('引用') + desc;
					desc = '<span class="font-primary" data-ref="true">'+LANG('引用')+'</span>' + desc;
				}

				var elm = $('<div class="desc text-truncate"/>').html(desc)
							.attr('title', title)
							.insertBefore(anchor);
				var logic = self.buildLogic(elm, data.Operator);
				// 更新前一个logic
				self.updateLogic(elm.prev('.logic'));

				elm.toggleClass('ex', data.Relation == 2);
				elm.toggleClass('ref', data.Type == 'ConditionRef');


				// 建立数据结构
				// 记录有效+号
				// 有上级锚点就可以构建+号
				// 有+号就可以构建data
				var uid = self.getUid(anchor);
				elm.attr('data-uid', uid);
				logic.attr('data-uid', uid);
				self.$levelData[uid] = data;
				self.$levelLogic[uid] = logic;
			}

			return anchor;
		},
		// 更新单条件数据
		updateLevelData: function(data){
			if(data){
				var self = this;
				var doms = self.$doms;
				var anchor = data.anchor;
				var uid = anchor.attr('data-uid');
				// 描述文本
				var desc = data.Title + '：' + data.Desc;
				var title = desc;

				if(data.Relation == 2){
					title = LANG('排除') + desc;
					desc = '<span class="font-danger">'+LANG('排除')+'</span>' + desc;
				}
				var elm = doms.level.find('[data-uid="'+uid+'"]').first();
				elm.html(desc).attr('title', title);
				elm.toggleClass('ex', data.Relation == 2);
				self.$levelData[uid] = data;
			}
			return this;
		},
		// 构建且或
		buildLogic: function(target, value){
			var self = this;
			var and = '<span data-id="1" data-type="and">' + LANG('且') + '</span>';
			var or = '<span data-id="2" data-type="or">' + LANG('或') + '</span>';
			var order = and + or; // 顺序

			if(value == 2){
				order = or + and;
			}

			var logic = $([
				'<div class="logic">' + order +
				'</div>'
			].join(''));

			if(target){
				logic.insertAfter(target);
			}
			self.updateLogic(logic);

			return logic;
		},
		// 更新且或样式
		updateLogic: function(logic){
			if(logic && logic.length){
				logic.toggle(!logic.next('a').length);
				logic.addClass('mr5');
				logic.removeClass('ml5');
				if(logic.next('.desc').length){
					logic.removeClass('mr5');
				}
				if(logic.prev('.lv').length){
					logic.addClass('ml5');
				}
			}
			return this;
		},
		// 获取且或结果
		getLogic: function(logic){
			if(logic && logic.length){
				return +logic.find('span:first').attr('data-id');
			}
			return 1;
		},
		setData: function(data){
			var self = this;
			var doms = self.$doms;

			util.each(data.Items, function(t){
				if(t){

					if(t.Items && t.Items.length){
						// 先构建一个层
						var anchor1 = self.addLevel(doms.anchor);
						// 循环里面的items
						util.each(t.Items, function(tt){
							if(tt){

								if(tt.Items && tt.Items.length){
									var anchor2 = self.addLevel(anchor1);
									util.each(tt.Items, function(ttt){
										if(ttt){

											if(ttt.Items && ttt.Items.length){
												var anchor3 = self.addLevel(anchor2);
												util.each(ttt.Items, function(tttt){
													if(tttt){
														tttt.Operator = ttt.Operator;
														self.setLevelData(tttt, anchor3);
													}

												});

											}else{
												ttt.Operator = tt.Operator;
												self.setLevelData(ttt, anchor2);
											}
										}
									});

								}else{
									tt.Operator = t.Operator;
									self.setLevelData(tt, anchor1);
								}
							}
						});

					}else{
						t.Operator = data.Operator;
						self.setLevelData(t, doms.anchor);
					}
				}

			});

			return self;
		},
		getData: function(){
			var self = this;
			var logics = self.$levelLogic;
			var data = util.clone(this.$levelData);
			// 最顶层
			var result = {
				Operator: 1,
				Items: []
			};
			var Items = result.Items;

			// 暂时用这粗劣的写法，以后优化
			util.each(data, function(item, key){
				if(key){
					var keys = key.split('-');
					switch (keys.length){
						case 2:
							result.Operator = self.getLogic(logics[key]);
							delete item.anchor;
							delete item.Operator;
							delete item.IsEdit;
							Items[keys[1]] = item;
							break;
						case 3:
							if(!Items[keys[1]]){
								Items[keys[1]] = {
									Operator: 1,
									Items: []
								}
							}
							Items[keys[1]].Operator = self.getLogic(logics[key]);
							delete item.anchor;
							delete item.Operator;
							delete item.IsEdit;
							Items[keys[1]].Items[keys[2]] = item;
							break;
						case 4:
							if(!Items[keys[1]]){
								Items[keys[1]] = {
									Operator: 1,
									Items: []
								}
							}
							if(!Items[keys[1]]['Items'][keys[2]]){
								Items[keys[1]]['Items'][keys[2]] = {
									Operator: 1,
									Items: []
								}
							}
							Items[keys[1]]['Items'][keys[2]].Operator = self.getLogic(logics[key]);
							delete item.anchor;
							delete item.Operator;
							delete item.IsEdit;
							Items[keys[1]]['Items'][keys[2]].Items[keys[3]] = item;
							break;
						case 5:
							if(!Items[keys[1]]){
								Items[keys[1]] = {
									Operator: 1,
									Items: []
								}
							}
							if(!Items[keys[1]]['Items'][keys[2]]){
								Items[keys[1]]['Items'][keys[2]] = {
									Operator: 1,
									Items: []
								}
							}
							if(!Items[keys[1]]['Items'][keys[2]]['Items'][keys[3]]){
								Items[keys[1]]['Items'][keys[2]]['Items'][keys[3]] = {
									Operator: 1,
									Items: []
								}
							}
							Items[keys[1]]['Items'][keys[2]]['Items'][keys[3]].Operator = self.getLogic(logics[key]);
							delete item.anchor;
							delete item.Operator;
							delete item.IsEdit;
							Items[keys[1]]['Items'][keys[2]]['Items'][keys[3]].Items[keys[4]] = item;
							break;
					}
				}
			});

			return Items.length ? result : null;
		},
		// 获取总描述
		getAllDesc: function(){
			var self = this;
			var doms = self.$doms;
			var desc = doms.level.text();
			// 简单获取
			desc = desc.replace(/且或/g, LANG(' 且 '))
							.replace(/或且/g, LANG(' 或 '))
							.replace(/且\)/g, ')')
							.replace(/或\)/g, ')')
							.replace(/且\s$/, '')
							.replace(/或\s$/, '')
							.replace(/且\s?\)$/, ')')
							.replace(/或\s?\)$/, ')')
							.replace(/且\s+\)/g, ')')
							.replace(/或\s+\)/g, ')');
			return desc;
		},
		reset: function(buildOne){
			var self = this;
			self.$levelData = {};
			self.$levelLogic = {};
			self.$hasRef = [];
			// 清空dom
			self.$doms.level.find('>div').remove();

			if(buildOne){
				self.addLevel(self.$doms.level.find('>a'));
			}

			return self;
		},
		verify: function(){
			// 弹窗之前需判断条件内容里是否已包含引用的条件，如果包含则弹窗提示：不允许保存包含引用条件的条件！
			if(this.$hasRef.length){
				return false;
			}
			return true;
		}
	});
	exports.conditionLevel = ConditionLevel;

	// 设置条件主模块弹窗
	var Condition = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'size': 'l',
				'title': LANG('设置条件'),
				'style': {
					'bodyClass': 'M-promotionCondition'
				},
				'buttonConfig': {
					'other': {
						'type':'button'
						,'layout':null
						,'value':LANG('保存条件')
						,'class':'btn btn-primary'
						,'width': 100
						,'attr':{'data-action':'onOther'}
						,'events':'click'
					}
				},
				'buttons':['cancel', 'ok', 'other'],
				'autoShow': true,
				'view_model':{
					'isEdit': false,
					'name': ''
				},
				// fire的事件名称
				'fire_name': 'setCommonOk'
			});

			this.$editData = null; // 编辑数据

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);
			var el = self.getDOM('body');

			$([
				'<div class="mt20 opCon"  ms-visible="!isEdit">',
					'<button class="btn btn-default copy mr20">'+ LANG('从现有条件复制') + '</button>',
					'<a class="empty valign-m">' + LANG('清空条件内容') + '</a>',
				'</div>',
				'<div class="mt20 mb20" ms-visible="isEdit">',
				 	'<label>' + LANG('名称：') + '</label>',
				 	'<input type="text" class="w400 ml10" ms-duplex-text="name"/>',
				'</div>',
				'<div class="mt20 mb20">' + LANG('条件内容：') + '</div>',
				'<div class="mt20" pub-name="conditionLevel" pub-mod="promotion/popwin/popwin.conditionLevel"/>',

			].join('')).appendTo(el);

			var doms = this.$doms || {};
			doms.empty = el.find('.opCon .empty');
			doms.copy = el.find('.opCon .copy');

			var config = {
			};

			self.uiBind(doms.empty, 'click', 'eventEmptyCondition');
			self.uiBind(doms.copy, 'click', 'eventCopyCondition');


			self.buildFromTemplate(config);

			self.create('saveCondition', SaveCondition, {});
		},
		afterBuildTemplate: function(ev){

		},
		load: function(id){
			var self = this;
			self.vm.$.isEdit = true;
			self.$doms.foot.find('[data-action="onOther"]').toggle(!self.vm.$.isEdit);
			// 编辑状态
			if(id){
				self.showLoading();
				pubjs.mc.send('condition/info', {'_id':+id}, self.afterLoad.bind(self));
			}else{
				// 新建状态
				this.$editData = {};
			}
			return self;
		},
		afterLoad: function(err, data){
			this.hideLoading();
			if (err){
				pubjs.alert(err.message);
				return false;
			}
			this.$editData = data;
			this.setData(data);
		},
		eventCopyCondition: function(evt, elm){
			var self = this;
			if(!self.get('copyCondition')){
				self.create('copyCondition', RefCondition);
			}
			self.get('copyCondition').show();
			return false;
		},
		eventEmptyCondition: function(evt, elm){
			if(this.$.conditionLevel){
				this.$.conditionLevel.reset();
			}
			return false;
		},
		// 复制条件
		onSelectCondition: function(ev){
			if(ev.param){
				this.$.conditionLevel.reset().setData(ev.param.Data);
			}
		},
		onOk: function(ev){
			var self = this;
			var data = self.getData();
			if(self.vm.$.isEdit){
				self.onOther(true);
			}else{

				var index = self.getConfig('index');
				// fire事件名称
				var fire_name = self.getConfig('fire_name');
				self.fire(fire_name, {
					index: index,
					type: 'condition',
					render: data.Desc,
					data: data
				});
				self.hide();
			}

			return false;
		},
		setData: function(data){
			var self = this;
			self.vm.$.name = data.Name;
			self.$.conditionLevel.setData(data.Data || data);
			return self;
		},
		getData: function(){
			var self = this;
			var mod = self.get('conditionLevel');
			if(mod){
				return {
					Data: mod.getData(),
					Desc: mod.getAllDesc()
				};
			}else{
				return {};
			}
		},
		reset: function(buildOne){
			var self = this;
			self.vm.reset();
			self.vm.$.name = LANG('新建条件_%1', util.date('YmdHis'));
			self.$editData = null;
			self.get('conditionLevel').reset(buildOne);
			self.$doms.foot.find('[data-action="onOther"]').show();
			return self;
		},
		// 保存条件和编辑条件
		onOther: function(isEdit){
			var self = this;
			var data = self.getData();
			var mod = self.get('conditionLevel');

			if(!data.Data){
				pubjs.alert(LANG('请先设置条件'));
				return false;
			}

			if(!mod.verify()){
				pubjs.alert(LANG('新建条件中包含引用外部条件，不能保存包含引用条件的条件'));
				return false;
			}

			// 是否编辑状态
			if(isEdit == true){
				data.Name = util.trim(self.vm.$.name || '');

				// 判断是否有_id
				if(self.$editData && +self.$editData._id){
					data._id = self.$editData._id;
				}

				if(!data.Name){
					pubjs.alert(LANG('请输入条件名称'));
					return false;
				}

				if(data.Name.length > 50){
					pubjs.alert(LANG('名称不超过50个字符'));
					return false;
				}
				// 判断新建还是编辑
				var url = data._id ? 'condition/update' : 'condition/add';
				self.showLoading();
				pubjs.mc.send(url, data, self.afterUpdate.bind(self), data);

			}else{
				// 在推广组模块下，保存条件会弹出新的弹层再保存，
				if(self.get('saveCondition')){
					self.get('saveCondition').reset().setData(data).show();
				}
			}
		},
		afterUpdate: function(err, data, updateData){
			var self = this;
			self.hideLoading();
			if (err){
				pubjs.alert(err.message);
				return false;
			}
			// 判断是否有引用条件，有推广组引用过，弹层同步更新的弹窗
			if(updateData && updateData._id && data && data.Campaigns){
				if(!self.get('updateNotice')){
					self.createAsync('updateNotice', 'promotion/popwin/popwin.updateNotice', {}, function(mod){
						if(mod){
							mod.setData(data, updateData).show();
						}
					});
				}else{
					self.get('updateNotice').setData(data, updateData).show();
				}
			}else{
				self.fire('updateCondition', data);
			}

			// pubjs.alert(LANG('保存成功'));
			self.hide();
		},
		setIndexConfig: function(index){
			this.setConfig('index', index);
			return this;
		}
	});
	exports.condition = Condition;

	// 保存条件
	var SaveCondition = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'size': 's',
				'title': LANG('保存条件'),
				'style': {
					'bodyClass': 'M-promotionConditionSave'
				},
				'autoShow': false
			});

			this.$data = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);
			var el = self.getDOM('body');

			$([
				'<div class="M-formConGroup">',
					'<label class="group-label">'+LANG('名称：')+'</label>',
					'<div class="group-content">',
						'<span pub-name="name" pub-mod="@base/common/input.text" />',
					'</div>',
				'</div>'

			].join('')).appendTo(el);

			var config = {
				'name': {
					'placeholder': LANG('请输入名称，不超过50个字符'),
					'width': '80%'
				}
			};

			self.buildFromTemplate(config);
		},
		afterBuildTemplate: function(ev){
		},
		onOk: function(ev){
			var self = this;
			var data = self.$data || {};
			data['Name'] = util.trim(self.$.name.getValue());

			if(!data.Name){
				pubjs.alert(LANG('请输入条件名称'));
				return false;
			}

			if(data.Name.length > 50){
				pubjs.alert(LANG('名称不超过50个字符'));
				return false;
			}

			self.showLoading();
			pubjs.mc.send('condition/add', data, self.afterSave.bind(self));
		},
		afterSave: function(err, data){
			this.hideLoading();
			if (err){
				pubjs.alert(err.message);
				return false;
			}
			this.hide();
			pubjs.alert(LANG('保存条件成功'));
		},
		setData: function(data){
			var self = this;
			self.$data = data;
			return self;
		},
		reset: function(){
			var self = this;
			self.$data = null;
			self.$.name.setValue('');
			return self;
		},
	});
	exports.saveCondition = SaveCondition;

	// 引用已保存条件
	var RefCondition = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'size': 'm',
				'title': LANG('引用已保存条件'),
				'style': {
					'bodyClass': 'M-promotionConditionRef'
				},
				'autoShow': false,
				'buttons': ['cancel', null],
				'selectEvent': 'selectCondition'
			});

			this.$data = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);
			var el = self.getDOM('body');

			$([
				'<div class="M-formConGroup">',
					'<span pub-name="grid" pub-mod="@base/grid.base" />',
				'</div>'

			].join('')).appendTo(el);

			var config = {
				'grid': {
					'url': 'condition/list',
					'reqType': 'websocket',
					'cols': [
						{name:'_id', text:"ID", width: 50, sort: true,'align': 'center'},
						{name:'Name', text: LANG('名称'), width: 230, render: 'renderName'},
						{name:'UpdateTime', text: LANG('更新时间'), width: 180, render: 'renderTime',align:'center'},
						{name:'op',text: LANG("操作"), type: 'op', render: 'renderOperate',width:120}
					],
					'hasExport': false,
					'hasAmount': false,
					'hasTab': false,
					'opClick': true,
					'pager': {
						'size': 10,
						'stepButton': true,
						'showSizeTypes': 0,
						'showJumper': 0
					},
					'list': {
						'rowSelect': false,
						'rowSelectOp': true
					}
				}
			};

			self.buildFromTemplate(config);
		},
		afterBuildTemplate: function(ev){
		},
		renderName: function(i, val, row, con){
			return $('<div class="text-truncate tl" title="' + val + '">' + val + '</div>').width(con.width);
		},
		renderTime: function(i, val){
			return util.date("Y-m-d H:i:s", val);
		},
		renderOperate: function(i, val, row) {
			return '<button data-op="select" class="btn btn-success">' + LANG('选择') + '</button>';
		},
		onListOpClick: function(ev) {
			var self = this;
			switch(ev.param.op) {
				case 'select':
					self.fire(self.getConfig('selectEvent'), ev.param.data);
					self.hide();
					break;
			}
			return false;
		},
		setData: function(data){
			var self = this;
			return self;
		},
		reset: function(){
			var self = this;
			return self;
		},
	});
	exports.refCondition = RefCondition;

	// 更新提示
	var UpdateNotice = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'size': 'm',
				'title': LANG('更新提示'),
				'style': {
					'bodyClass': 'M-promotionConditionNotice'
				},
				'buttonConfig':{
					// 确定按钮样式
					'ok': {
						'value':LANG('同步更新')
					}
				},
				'autoShow': false,
				'selectEvent': 'updateNotice',
				'view_model': {
					'name': ''
				}
			});

			this.$updateData = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);
			var el = self.getDOM('body');

			$([
				'<div class="M-formConGroup">',
					'<div class="alert a-is-warning tips mb10">',
						'<em class="uk-icon-exclamation-circle mr10" style="font-size:14px"/>',
						'<span ms-text="name"/>',
						'<span class="ml10">'+LANG('条件被以下计划推广组引用，确认更新将会同步该条件内容！')+'</span>',
					'</div>',
					'<span pub-name="grid" pub-mod="@base/grid.base" />',
				'</div>'

			].join('')).appendTo(el);

			var config = {
				'grid': {
					'url': '',
					'reqType': 'websocket',
					'cols': [
						{name:'PlanId', text:"计划ID", width: 50, sort: true,'align': 'center'},
						{name:'PlanName', text: LANG('计划名称'), width: 230, render: 'renderName'},
						{name:'_id', text:"推广组ID", width: 50, sort: true,'align': 'center'},
						{name:'Name', text: LANG('推广组名称'), width: 230, render: 'renderName'},
					],
					'hasExport': false,
					'hasAmount': false,
					'hasTab': false,
					'opClick': false,
					'hasSearch': false,

					'pager': {
						'size': 10,
						'stepButton': true,
						'showSizeTypes': 0,
						'showJumper': 0
					},
					'list': {
						'rowSelect': false,
						'rowSelectOp': true
					}
				}
			};

			self.buildFromTemplate(config);
		},
		afterBuildTemplate: function(ev){
		},
		renderName: function(i, val, row, con){
			return $('<div class="text-truncate tl" title="' + val + '">' + (val||'') + '</div>').width(con.width);
		},
		setData: function(data, updateData){
			var self = this;
			if(self.get('grid')){
				self.$.grid.setData(data.Campaigns);
			}
			self.vm.$.name = '#' + updateData.Name + '#';
			self.$updateData = updateData;
			return self;
		},
		onOk: function(ev){
			var self = this;
			// 同步更新状态，加入特殊标记
			self.$updateData['UpdateRef'] = true;
			self.showLoading();
			pubjs.mc.send('condition/update', self.$updateData, self.afterSave.bind(self));
			return false;
		},
		afterSave: function(err, data){
			this.hideLoading();
			if (err){
				pubjs.alert(err.message);
				return false;
			}
			this.fire('updateCondition', data);
			this.hide();
			pubjs.alert(LANG('更新成功'));
		},
		reset: function(){
			var self = this;
			if(self.get('grid')){
				self.$.grid.setData([]);
			}
			self.$updateData = null;
			self.vm.reset();
			return self;
		}
	});
	exports.updateNotice = UpdateNotice;

	// 继承tooltip
	var ConditionTip = tip.tooltip.extend({
		init: function(config){
			config = pubjs.conf(config, {
			});

			this.Super('init', arguments);
		},
		show: function(){
			var self = this;
			self.Super('show', arguments);
			var el = self.getDOM();
			var c = self.getConfig();
			var offset = el.offset();
			var w = $(window).width();
			// 超出窗口范围的，重新计算
			var diff = offset.left + el.width() - w;
			if(diff > 0 ){
				if(c.arrowAlign){
					self.$doms.arrow.css('left', diff + 1);
				}
				el.css('left', offset.left - diff);
			}
			return self;
		}
	});
	exports.conditionTip = ConditionTip;
});